<template>
	<view class="container">
		<!-- 登录表单 -->
		<up-form
			labelPosition="left"
			:model="form"
			:rules="rules"
			ref="formRef"
		>
			<!-- 账号输入框 -->
			<up-form-item
				label="账号"
				prop="userAccount"
				borderBottom
				label-width="150rpx"
			>
				<up-input
					v-model="form.userAccount"
					border="none"
					placeholder="请输入账号"
				></up-input>
			</up-form-item>

			<!-- 密码输入框 -->
			<up-form-item
				label="密码"
				prop="userPassword"
				borderBottom
				label-width="150rpx"
			>
				<up-input
					v-model="form.userPassword"
					border="none"
					placeholder="请输入密码"
					password
				></up-input>
			</up-form-item>
		</up-form>

		<!-- 登录按钮 -->
		<up-button
			type="primary"
			text="登录"
			customStyle="margin-top: 50px"
			@click="submit"
			shape="circle"
		></up-button>

		<!-- 注册按钮 -->
		<navigator
			url="/pages/register/register"
			hover-class="navigator-hover"
		>
			<up-button
				type="default"
				text="注册新用户"
				customStyle="margin-top: 10px"
				shape="circle"
			></up-button>
		</navigator>
	</view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import myAxios from "@/plugins/myAxios";

// 表单数据
const form = ref({
	userAccount: "",
	userPassword: "",
});

// 表单校验规则
const rules = {
	userAccount: [
		{ required: true, message: "请输入账号", trigger: "blur" },
	],
	userPassword: [
		{
			required: true,
			message: "请输入密码",
			trigger: "blur",
		},
	],
};

// 表单引用
const formRef = ref();

// 登录逻辑
const submit = () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			// 表单校验通过后提交
			await onSubmit();
		} else {
			uni.showToast({
				title: "请检查表单输入",
				icon: "none",
				duration: 2000,
			});
		}
	});
};

const onSubmit = async () => {
	try {
		// 提交数据到后端
		const res = await myAxios.post("/user/login", {
			userAccount: form.value.userAccount,
			userPassword: form.value.userPassword,
		});
		console.log(res, "登录返回信息");

		// 登录成功逻辑
		if (res.code === 0 && res.data) {
			const redirectUrl = getApp().globalData.redirectUrl || "/pages/index/index";
			uni.showToast({
				title: "登录成功",
				icon: "success",
				duration: 2000,
			});
			uni.reLaunch({
				url: redirectUrl,
			});
		} else {
			// 登录失败逻辑
			uni.showToast({
				title: "登录失败: " + res.description,
				icon: "none",
				duration: 2000,
			});
		}
	} catch (error) {
		// 异常处理
		console.error(error);
		uni.showToast({
			title: "登录异常，请稍后重试",
			icon: "none",
			duration: 2000,
		});
	}
};
</script>

<style lang="scss">
.container {
	padding: 15px;
}
</style>
